﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceModel.Activities;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using System.Xml;
using App.Codes;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;
using Newtonsoft.Json;
 using App.SendMessage;

namespace Langben.App.Controllers
{
    /// <summary>
    /// Complaint
    /// </summary>
    public class ComplaintController : BaseController
    {
        SysEntities db=new SysEntities();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }
 
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<Complaint> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);

            foreach (var complaint in queryData)
            {
                 
                string officespace = new ClsCon().GetFieldValue("select top 1 [Name] from [OfficeSpace] where RowGuid='" + complaint.OfficeSpace + "'");
                if (!string.IsNullOrEmpty(officespace))
                {
                    complaint.OfficeSpace = officespace;
                }

                string person = new ClsCon().GetFieldValue("select top 1 MyName from SysPerson where Id='" + complaint.Person + "'");

                if (!string.IsNullOrEmpty(person))
                {
                    complaint.Person = person;
                }

            }


            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    RowGuid = s.RowGuid
					,CreateTime = s.CreateTime
					,CreatePerson = s.CreatePerson
					,Floor = s.Floor
					,OfficeSpace = s.OfficeSpace
                    ,
                    Person = s.Person
					,Describe = s.Describe
					,ComplainantName = s.ComplainantName
					,ComplainantTel = s.ComplainantTel
					
                }

                    )
            });
        }
         
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            Complaint item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
         
        public ActionResult Create(string id)
        { 
            
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
       
        public ActionResult Create(Complaint entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                entity.CreateTime = DateTime.Now;
                entity.CreatePerson = currentPerson;
              
                entity.RowGuid = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，Complaint的信息的Id为" + entity.RowGuid,"Complaint"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，Complaint的信息，" + returnValue,"Complaint"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        public ActionResult Complaint(string id)
        {

            return View();
        }

        [HttpPost]
        public ActionResult Complaint(Complaint entity)
        {
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                entity.CreateTime = DateTime.Now;
                entity.CreatePerson = currentPerson;

                entity.RowGuid = Result.GetNewId();
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    SysPerson admin = new SysEntities().SysPerson.SingleOrDefault(s => s.Name == "Admin");
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，Complaint的信息的Id为" + entity.RowGuid,
                        "Complaint"
                        ); //写入日志 

                    //发短信。
                    //SmsService sms=new SmsService();

                    try
                    {
                        SmsServiceSoapClient sms = new SmsServiceSoapClient();
                        var lingdaocontent = db.ComplaintMessage.SingleOrDefault(s => s.Type == "领导").Content;
                        var beitoushucontent = db.ComplaintMessage.SingleOrDefault(s => s.Type == "被投诉人").Content;
                        var toushucontent = db.ComplaintMessage.SingleOrDefault(s => s.Type == "投诉人").Content;

                        if (!string.IsNullOrEmpty(entity.Person) && entity.Person!="请选择")
                        {
                            SysPerson beitoushuren = new SysPersonBLL().GetById(entity.Person);
                            if (!string.IsNullOrEmpty(beitoushuren.MobilePhoneNumber))
                            {
                                beitoushucontent = beitoushucontent.Replace("{投诉时间}", DateTime.Now.ToShortDateString());
                                beitoushucontent = beitoushucontent.Replace("{投诉分类}", entity.Type);
                                XmlNode beitoushuNode = sms.SendEx("chonglang", "757783e6cf17b26f", "808", beitoushuren.MobilePhoneNumber, "",
                            beitoushucontent + "【政务服务中心】");
                                //插入记录
                                if (beitoushuNode != null)
                                {
                                    var count = beitoushuNode.SelectSingleNode("/SuccessCount");
                                    if (!string.IsNullOrEmpty(count.InnerText))
                                    {
                                        int countsum = Convert.ToInt32(count.InnerText);
                                        if (countsum > 0)
                                        {
                                            Message message=new Message();
                                            message.Content = beitoushucontent + "【政务服务中心】";
                                            message.CreateTime = DateTime.Now;
                                            message.RowGuid = Convert.ToString(Guid.NewGuid());
                                            message.State = "发送成功";
                                            message.TelNo = beitoushuren.MobilePhoneNumber;
                                            new MessageBLL().Create(ref validationErrors, message);
                                        }
                                        else
                                        {
                                            Message message = new Message();
                                            message.Content = beitoushucontent + "【政务服务中心】";
                                            message.CreateTime = DateTime.Now;
                                            message.RowGuid = Convert.ToString(Guid.NewGuid());
                                            message.State = "发送失败";
                                            message.TelNo = beitoushuren.MobilePhoneNumber;
                                            new MessageBLL().Create(ref validationErrors, message);
                                        }
                                    }
                                }
                                
                               

                            }

                        }
                        if (!string.IsNullOrEmpty(entity.ComplainantTel))
                        {

                            XmlNode toushuNode = sms.SendEx("chonglang", "757783e6cf17b26f", "808", entity.ComplainantTel, "",
                            toushucontent + "【政务服务中心】");
                            //插入记录
                            if (toushuNode != null)
                            {
                                var count = toushuNode.SelectSingleNode("/SuccessCount");
                                if (!string.IsNullOrEmpty(count.InnerText))
                                {
                                    int countsum = Convert.ToInt32(count.InnerText);
                                    if (countsum > 0)
                                    {
                                        Message message = new Message();
                                        message.Content = toushucontent + "【政务服务中心】";
                                        message.CreateTime = DateTime.Now;
                                        message.RowGuid = Convert.ToString(Guid.NewGuid());
                                        message.State = "发送成功";
                                        message.TelNo = entity.ComplainantTel;
                                        new MessageBLL().Create(ref validationErrors, message);
                                    }
                                    else
                                    {
                                        Message message = new Message();
                                        message.Content = toushucontent + "【政务服务中心】";
                                        message.CreateTime = DateTime.Now;
                                        message.RowGuid = Convert.ToString(Guid.NewGuid());
                                        message.State = "发送失败";
                                        message.TelNo = entity.ComplainantTel;
                                        new MessageBLL().Create(ref validationErrors, message);
                                    }
                                }
                            }


                        }
                        if (!string.IsNullOrEmpty(admin.MobilePhoneNumber))
                        {
                            string beitoushurenname = string.Empty;
                            if (!string.IsNullOrEmpty(entity.Person) && entity.Person != "请选择")
                            {
                                SysPerson beitoushuren = new SysPersonBLL().GetById(entity.Person);
                                beitoushurenname = beitoushuren.MyName;
                            }

                            lingdaocontent = lingdaocontent.Replace("{被投诉人}", beitoushurenname);
                            lingdaocontent = lingdaocontent.Replace("{投诉时间}",DateTime.Now.ToShortDateString());
                            lingdaocontent = lingdaocontent.Replace("{投诉分类}", entity.Type);
                             
                            XmlNode beitoushuNode = sms.SendEx("chonglang", "757783e6cf17b26f", "808", admin.MobilePhoneNumber, "",
                           lingdaocontent + "【政务服务中心】");
                            //插入记录
                            if (beitoushuNode != null)
                            {
                                var count = beitoushuNode.SelectSingleNode("/SuccessCount");
                                if (!string.IsNullOrEmpty(count.InnerText))
                                {
                                    int countsum = Convert.ToInt32(count.InnerText);
                                    if (countsum > 0)
                                    {
                                        Message message = new Message();
                                        message.Content = lingdaocontent + "【政务服务中心】";
                                        message.CreateTime = DateTime.Now;
                                        message.RowGuid = Convert.ToString(Guid.NewGuid());
                                        message.State = "发送成功";
                                        message.TelNo = admin.MobilePhoneNumber;
                                        new MessageBLL().Create(ref validationErrors, message);
                                    }
                                    else
                                    {
                                        Message message = new Message();
                                        message.Content = lingdaocontent + "【政务服务中心】";
                                        message.CreateTime = DateTime.Now;
                                        message.RowGuid = Convert.ToString(Guid.NewGuid());
                                        message.State = "发送失败";
                                        message.TelNo = admin.MobilePhoneNumber;
                                        new MessageBLL().Create(ref validationErrors, message);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex )
                    {
                        return Json(ex.Message);
                    }


                    
                     
                    return Json("建议投诉成功。");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，Complaint的信息，" + returnValue, "Complaint"
                        ); //写入日志                      
                    return Json(Suggestion.InsertFail + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            Complaint item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, Complaint entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，Complaint信息的Id为" + id,"Complaint"
                        );//写入日志                           
                    return Json(Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，Complaint信息的Id为" + id + "," + returnValue, "Complaint"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.IComplaintBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public ComplaintController()
            : this(new ComplaintBLL()) { }

        public ComplaintController(ComplaintBLL bll)
        {
            m_BLL = bll;
        }


        public string GetOfficePlace(string floor)
        {
            DataTable dtOfficePlace = new ClsCon().CreatDaTable("SELECT RowGuid,Name FROM dbo.OfficeSpace WHERE Floor='" + floor + "'");
            return JsonConvert.SerializeObject(dtOfficePlace );
        }

        public string GetPerson(string workspace)
        {
            DataTable dtOfficePlace = new ClsCon().CreatDaTable("select Id,MyName from sysperson where OfficeSpaceGuid='" + workspace + "'");
            return JsonConvert.SerializeObject(dtOfficePlace );
        }

        /// <summary>
        ///  导出Excle /*在6.0版本中 新增*/
        /// </summary>
        /// <param name="param">Flexigrid传过到后台的参数</param>
        /// <returns></returns>      
        [HttpPost]
        public ActionResult Export(string id, string title, string field, string sortName, string sortOrder, string search)
        {
            string[] titles = title.Split(',');//如果确定显示的名称，可以直接定义
            string[] fields = field.Split(',');
            List<Complaint> queryData = m_BLL.GetByParam(id, sortOrder, sortName, search);

            return Content(WriteExcle(titles, fields, queryData.ToArray()));
        }
        
    }
}


